<template>
  <div class="content-left">
    <el-menu v-if="screenWidth > 1024" router :default-active="onRoutes" class="el-menu-vertical-demo" :collapse="!isCollapse"
      background-color="#2F4050" text-color="#a7b1c2">
      <template v-for="(item,index) in menuList">
        <template v-if="item.children&&item.children.length && (item.meta.isShow || item.state == 1 || role == 'admin')">
          <el-submenu :index="`menu_${index}`" :key="`menu_${index}`" class="children">
            <template slot="title">
              <i class="xian" v-if="onRoutes == item.path"></i>
              <i :class="'iconfont' + item.meta.icon"></i>
              <span slot="title">{{ $t(item.meta.title) }}</span>
            </template>
            <template v-for="(subItem,indexSub) in item.children">
              <template v-if="subItem.meta.state == 1 || role == 'admin'">
                <template v-if="item.path == '/reportForm'">
                  <el-menu-item :index="'/'+subItem.path.split('/')[1]+'/'+subItem.meta.index" :key="`indexSub_${indexSub}`"
                    v-if="subItem.meta.icon">
                    <i class="xian" v-if="onRoutes == subItem.path"></i>
                    <i :class="subItem.meta.icon"></i>
                    <span slot="title">{{  $t(subItem.meta.title) }}</span>
                  </el-menu-item>
                </template>
                <template v-else>
                  <el-menu-item :index="subItem.path" :key="`indexSub_${indexSub}`"
                    v-if="subItem.meta.icon && subItem.path != '/customPage'">
                    <i class="xian" v-if="onRoutes == subItem.path"></i>
                    <i :class="'iconfont' + subItem.meta.icon"></i>
                    <span slot="title">{{  $t(subItem.meta.title) }}</span>
                  </el-menu-item>
                </template>
              </template>
            </template>

          </el-submenu>
        </template>
        <template v-else>
          <el-menu-item :index="item.path" :key="index" v-if="item.meta.icon && (item.meta.state == 1 || item.isShow || role == 'admin')">
            <i class="xian" v-if="onRoutes == item.path"></i>
            <i :class="'iconfont' + item.meta.icon"></i>
            <span slot="title">{{$t(item.meta.title)}}</span>
          </el-menu-item>
        </template>
      </template>
    </el-menu>

    <div v-if="screenWidth <= 1024">
      <el-drawer title="标题" :with-header="false" :visible.sync="isCollapse" direction="ltr" size="200" :before-close="handleClose">
        <el-menu router :default-active="onRoutes" class="el-menu-vertical-demo" background-color="#2F4050" text-color="#a7b1c2">
          <template v-for="(item,index) in menuList">
            <template v-if="item.children&&item.children.length && (item.meta.isShow || item.state == 1 || role == 'admin')">
              <el-submenu :index="`menu_${index}`" :key="`menu_${index}`" class="children">
                <template slot="title">
                  <i class="xian" v-if="onRoutes == item.path"></i>
                  <i :class="'iconfont' + item.meta.icon"></i>
                  <span slot="title">{{ $t(item.meta.title) }}</span>
                </template>
                <template v-for="(subItem,indexSub) in item.children">
                  <template v-if="subItem.meta.state == 1 || role == 'admin'">
                    <template v-if="item.path == '/reportForm'">
                      <el-menu-item :index="'/'+subItem.path.split('/')[1]+'/'+subItem.meta.index" :key="`indexSub_${indexSub}`"
                        v-if="subItem.meta.icon">
                        <i class="xian" v-if="onRoutes == subItem.path"></i>
                        <i :class="subItem.meta.icon"></i>
                        <span slot="title">{{ $t(subItem.meta.title) }}</span>
                      </el-menu-item>
                    </template>
                    <template v-else>
                      <el-menu-item :index="subItem.path" :key="`indexSub_${indexSub}`"
                        v-if="subItem.meta.icon && subItem.path != '/customPage'">
                        <i class="xian" v-if="onRoutes == subItem.path"></i>
                        <i :class="'iconfont' + subItem.meta.icon"></i>
                        <span slot="title">{{ $t(subItem.meta.title) }}</span>
                      </el-menu-item>
                    </template>
                  </template>
                </template>

              </el-submenu>
            </template>
            <template v-else>
              <el-menu-item :index="item.path" :key="index"
                v-if="item.meta.icon && (item.meta.state == 1 || item.isShow || role == 'admin')">
                <i class="xian" v-if="onRoutes == item.path"></i>
                <i :class="'iconfont' + item.meta.icon"></i>
                <span slot="title">{{$t(item.meta.title)}}</span>
              </el-menu-item>
            </template>
          </template>
        </el-menu>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { userAdmin } from "@/api/userAdmin"
export default {
  data () {
    return {
      timer: false,
      menuList: [],
      tableData: [],
      count: 0,
      role: ""
    };
  },
  props: {
    isCollapse: Boolean,
    screenWidth: Number
  },
  // watch: {
  //   screenWidth(val){
  //     console.log(1123)
  //       if(!this.timer){
  //           this.screenWidth = val
  //           this.timer = true
  //           setTimeout(() => {
  //               this.timer = false
  //           },400)
  //       }
  //   }
  // },
  computed: {
    onRoutes () {
      //  return "/" + this.$route.path.split("/")[1];
      if (this.$route.meta.path) {
        return "/" + this.$route.meta.path.split("/")[1];
      } else {
        return "/" + this.$route.path.split("/")[1];
      }
    },
  },
  async created () {
    this.role = localStorage.getItem('userName')
    console.log(this.role, "?????????????????????????????")
    // console.log(this.$router.options)
    // this.menuList = this.$router.options.routes[0].children
    // this.$router.go(0)
    await this.cumLinksList()
    // this.onLayoutResize()
    this.findMenusByUser()
  },
  methods: {
    handleClose () {
      this.$emit("close", false)
    },
    // onLayoutResize(){
    //     const that = this
    //     window.onresize = () => {
    //         return (() => {
    //             window.screenWidth = document.body.clientWidth
    //             that.screenWidth = window.screenWidth
    //         })()
    //     }
    // },
    findMenusByUser () {
      userAdmin.findMenusByUser().then(res => {
        if (res.code == 200) {
          let menusList = this.addIsShowField(res.data).filter(item => item.menuType == 'M')
          let routerArr = JSON.parse(JSON.stringify(this.$router.options.routes[0].children))
          console.log(JSON.parse(JSON.stringify(routerArr)), 111)
          routerArr.forEach(item => {
            const indexTemp = menusList.findIndex(el => item.path == el.url)
            if (indexTemp > -1) {
              let children1 = menusList[indexTemp].children
              let children2 = item.children || []
              if (children1 && children1.length) {
                let onlyInMenusList = children1.filter(menuItem => {
                  const indexTemp = children2.findIndex(routerItem => routerItem.path === menuItem.url);
                  return indexTemp === -1;
                });
                if (onlyInMenusList.length) {
                  onlyInMenusList.forEach((item1, i) => {
                    if (item1) {
                      children2.push({
                        path: '/customPage?url=' + item1.url,
                        name: 'customPage',
                        component: () => import('@/page/customPage/index.vue'),
                        meta: {
                          title: item1.menuName,
                          icon: " icon-baobiao-xianxing",
                          url: item1.url,
                          index: new Date().getTime(),
                          state: item1.state,
                        }

                      });
                      item.meta.children.push('/customPage')

                      this.$router.addRoute('customPage', {
                        path: '/customPage?url=' + item1.url,
                        name: 'customPage',
                        component: () => import('@/page/customPage/index.vue'),
                        meta: {
                          title: item1.name,
                          icon: " icon-baobiao-xianxing",
                          url: item1.url,
                          index: new Date().getTime(),
                          state: item1.state,
                        },
                      });
                    }
                  });
                }


              } else {
                item.meta.state = menusList[indexTemp].state
                item.meta.isShow = menusList[indexTemp].isShow
              }

            }
          })

          const missingItems = [];
          menusList.forEach(menuItem => {
            const indexTemp = routerArr.findIndex(item => item.path === menuItem.url);
            if (indexTemp === -1) {
              missingItems.push(menuItem);
            }
          });
          console.log(missingItems, 'sddsf>>>>>>>>>>>')
          // const index = routerArr.findIndex(item => item.path == '/reportForm')
          missingItems.forEach((item, index) => {
            if (item.children && item.children.length) {
              routerArr.push({
                path: '/reportForm' + item.fid,
                name: 'reportForm' + item.fid,
                component: () => import('@/page/reportForm/index.vue'),
                meta: {
                  title: item.menuName,
                  icon: " icon-baobiao-xianxing",
                  children: ['/reportFormInfo'],
                  fid: item.fid,
                  url: item.url,
                  state: item.state
                },
                children: []
              })

              item.children.forEach(item1 => {
                const temp = {
                  path: '/customPage?url=' + item1.url,
                  name: 'customPage',
                  component: () => import('@/page/customPage/index.vue'),
                  meta: {
                    title: item1.menuName,
                    icon: " icon-baobiao-xianxing",
                    url: item1.url,
                    index: new Date().getTime(),
                    state: item1.state
                  }
                }

                routerArr.forEach(item2 => {
                  if (item2.meta.fid == item.fid) {
                    item2.children.push(temp)
                  }
                })

              })
            } else {
              const temp = {
                path: '/customPage?url=' + item.url,
                name: 'customPage',
                component: () => import('@/page/customPage/index.vue'),
                meta: {
                  title: item.menuName,
                  icon: " icon-baobiao-xianxing",
                  url: item.url,
                  index: new Date().getTime(),
                  state: item.state
                }
              }
              routerArr.push(temp)
            }
          })
          // const index = routerArr.findIndex(item => item.path == '/reportForm')
          // const keyId = menusList.findIndex(item => item.url == '/reportForm')
          // console.log(keyId)
          // if(keyId > -1){
          //   routerArr[index].children = []
          //   this.tableData.forEach((item,key) => {
          //     if(menusList[keyId].children&&menusList[keyId].children.length){
          //       const i = menusList[keyId].children.findIndex(item1 => item1.menuName == item.name)
          //       let el = menusList[keyId].children[i]
          //       console.log(el,55)
          //       if(el){
          //         const temp = {
          //             path: '/'+el.url.split('/')[1]+'/:id',
          //             name: el.url.split('/')[1]+'/:id',
          //             component: () => import('@/page/reportForm/reportFormInfo.vue'),
          //             meta: {
          //                 title: item.name,
          //                 icon: item.icon,
          //                 url:item.url,
          //                 index:i
          //             }
          //         }
          //         routerArr[index].children.push(temp)
          //         this.$router.addRoute('reportForm', {
          //           path: '/'+el.url.split('/')[1]+'/:id',
          //           name: el.url.split('/')[1]+'/:id',
          //           component: () => import('@/page/reportForm/reportFormInfo.vue'),
          //           meta: {
          //             title: item.name,
          //             icon: item.icon,
          //             url:item.url,
          //             index:i
          //           },
          //         });
          //       }
          //     }
          //   })
          // }
          // console.log(JSON.parse(JSON.stringify(routerArr)),222)
          let menuListArr = []
          routerArr.forEach(item => {
            menusList.forEach(el => {
              if (item.path == el.url || item.meta.url == el.url) {
                item.meta.title = item.meta.title
                item.meta.orderNum = parseInt(el.orderNum)
                item.meta.isShow = el.isShow
                menuListArr.push(item)
              }
            })
          })
          console.log(JSON.parse(JSON.stringify(menuListArr)), 333)
          // menusList.forEach(item => {
          //   menuListArr.forEach(el => {
          //     if (item.url == el.path) {
          //       if (el.children) {
          //         el.children = el.children.filter(item1 => {
          //           const index = item.children.findIndex(el1 => {
          //             return item1.path.split('/')[1] == el1.url.split('/')[1]
          //           })
          //           if (index > -1) {
          //             return item1
          //           }
          //         })
          //       }

          //     }
          //   })
          // })

          menusList.forEach(item => {
            menuListArr.forEach(el => {
              if (item.url == el.path) {
                if (el.children) {
                  el.children = el.children.filter(item1 => {
                    const index = item.children.findIndex(el1 => {
                      if (item1.path.split('/')[1] == el1.url.split('/')[1]) {
                        return item1.path.split('/')[1] == el1.url.split('/')[1]
                      } else {
                        if (item1.name == 'customPage') {
                          if (item1.path && item1.path.indexOf('?') > -1) {
                            let urlPath = item1.path
                            let queryPart = urlPath.split('?')[1];
                            let queryValue = queryPart.split('=')[1];
                            let url = decodeURIComponent(queryValue)
                            if (url == el1.url) {
                              return el1
                            }
                          }

                        }
                      }

                    })
                    if (index > -1) {
                      item1.meta.state = item.children[index].state
                      return item1
                    }
                  })
                }

              }
            })
          })
          this.menuList = menuListArr.sort(this.compare('orderNum'));
          console.log(this.menuList, 515151515)
        }
      })
    },
    compare (propertyName) {
      return function (object1, object2) {
        var value1 = object1.meta[propertyName];
        var value2 = object2.meta[propertyName];
        if (value2 < value1) {
          return 1;
        } else if (value2 > value1) {
          return -1;
        } else {
          return 0;
        }
      }
    },
    cumLinksList () {
      userAdmin.cumLinksList({}).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.rows
        }
      })
    },
    addIsShowField (items) {
      return items.map(item => {
        let isShowInChildren = true;
        if (Array.isArray(item.children) && item.children.length > 0) {
          isShowInChildren = item.children.every(child => child.state === 0);
        }

        return {
          ...item,
          isShow: !isShowInChildren
        };
      });
    }
  },
};
</script>

<style scoped>
.content-left {
  height: calc(100vh - 60px);
  overflow: auto;
}
.content-left >>> .el-menu {
  height: 100%;
  border-right: none;
}
.content-left >>> .el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  height: 100%;
}
.el-menu-vertical-demo {
  background: #545c64;
}
.content-left .is-active {
  background: #293846 !important;
}
.iconfont {
  font-size: 20px;
  margin-right: 5px;
}
.el-menu-item.is-active {
  color: #d59dff;
}
.children {
  position: relative;
}
.xian {
  display: inline-block;
  width: 5px;
  height: 100%;
  background: #d59dff;
  margin-right: 10px;
  position: absolute;
  top: 50%;
  left: 5px;
  transform: translateY(-50%);
}
</style>
<style>
.el-menu-item.is-active {
  color: #d59dff;
}
.el-menu-item:hover i,
.el-menu-item:hover span {
  color: #d59dff !important;
}
.el-submenu__title:hover i,
.el-submenu__title:hover span {
  color: #d59dff !important;
}
</style>